import { _decorator, Component, Node, UIOpacity, Label, EventTouch } from 'cc';
import { Global } from '../Global';
import { store } from '../map/MapConfig';
const { ccclass, property } = _decorator;

@ccclass('StoreManage')
export class StoreManage extends Component {

    @property(Node)
    private buttons: Node = null

    start() {
        this.init()
        Global.storeManage = this
        this.cancel()
    }

    update(deltaTime: number) {

    }

    init() {
        let i = 0
        for (const buttonKey in store) {
            const button = this.buttons.children[i++]
            button.getChildByName('Label').getComponent(Label).string = store[buttonKey].label
            button.getChildByName('Button').name = buttonKey
        }
    }

    cancel() {
        this.node.getComponent(UIOpacity).opacity = 0
        this.node.active = false
        Global.key.globalMoveKey = false
    }

    openStore() {
        Global.key.globalMoveKey = true
        this.node.active = true
        this.node.getComponent(UIOpacity).opacity = 255
    }

    buttonClick(event: EventTouch) {
        if (event.target.name === 'cancel') {
            this.cancel()
            return
        }
        const storeEvent = store[event.target.name]
        const state = Global.hero._heroState

        // 检查消耗
        const gold = state.state.money + storeEvent.gold
        if (gold < 0) {
            Global.popUtil.popUp('你没有足够的金币！')
            return
        }
        const exper = state.state.exper + storeEvent.exper
        if (exper < 0) {
            Global.popUtil.popUp('你没有足够的经验！')
            return
        }

        // 消耗
        if (storeEvent.gold) {
            state.state.money += storeEvent.gold
        }
        if (storeEvent.exper) {
            state.state.exper += storeEvent.exper
        }

        // 提升状态
        if (storeEvent.level) {
            state.state.level += storeEvent.level
        }
        if (storeEvent.defense) {
            state.fight.defense += storeEvent.defense
        }
        if (storeEvent.magicDefense) {
            state.fight.magicDefense += storeEvent.magicDefense
        }
        if (storeEvent.life) {
            state.fight.life += storeEvent.life
        }
        if (storeEvent.atk) {
            state.fight.atk += storeEvent.atk
        }

    }
}

